package com.racetime.controller;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.racetime.po.User;
import com.racetime.service.UserService;
import com.racetime.serviceImpl.UserServiceImpl;
import com.racetime.util.MyLogger;
import com.racetime.util.ServiceAgent;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.logging.Logger;

/**
 * @author : Ice'Clean
 * @date : 2021-05-21
 *
 * 接收所有与用户操作有关的请求
 */
public class UserServlet extends BaseServlet {

    Logger servletLogger = MyLogger.getLogger("servlet");
    Logger userLogger = MyLogger.getLogger("userLogin");

    /**
     * 用户服务的动态代理
     */
    UserService userService = (UserService) new ServiceAgent(new UserServiceImpl()).getAgent();

    /**
     * 接收登录请求
     */
    public void login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*");

        // 获取用户名和密码
        String userName = request.getParameter("userName");
        String userPass = request.getParameter("userPass");

        servletLogger.info("【登录请求】用户名：" + userName + "， 密码：" + userPass);

        // 执行登录判断
        User user = userService.loginUser(userName, userPass);

        // 不为 null 表示登录成功
        if (user != null) {
            ObjectMapper mapper = new ObjectMapper();

            // 成功的话保存用户信息
            HttpSession session = request.getSession();
            session.setAttribute("user", user);
            userLogger.info("【登录请求】用户 " + user.getUserName() + " 登录成功");
            response.getWriter().write(mapper.writeValueAsString(user));
        } else {
            userLogger.info("【登录请求】用户 "+ userName +" 登录失败");
            response.getWriter().write("error");
        }
    }

    /**
     * 接收登录请求
     */
    public void register(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*");

        // 获取用户名和密码
        String userName = request.getParameter("userName");
        String userPass = request.getParameter("userPass");

        servletLogger.info("【注册请求】用户名：" + userName + "， 密码：" + userPass);

        // 判断用户名是否已存在
        ObjectMapper mapper = new ObjectMapper();
        if (userService.findUserByUserName(userName) == null) {
            // 注册新用户，并将用户实体发送给给前端
            User user = userService.createNewUser(userName, userPass);
            userLogger.info("【注册请求】新用户 " + user);
            response.getWriter().write(mapper.writeValueAsString(user));
        }else {
            // 返回空用户
            userLogger.info("【注册请求】用户名 "+ userName +" 已经存在，注册失败");
            response.getWriter().write(mapper.writeValueAsString(new User()));
        }
    }

    /**
     * 获取用户数据
     */
    public void getUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*");

        // 获取用户 id，然后在数据库中找出来
        int userId = Integer.parseInt(request.getParameter("userId"));
        User user = userService.findUserById(userId);

        // 返回给前端
        ObjectMapper mapper = new ObjectMapper();
        if (user != null) {
            userLogger.info("【用户数据请求】用户 " + user);
            response.getWriter().write(mapper.writeValueAsString(user));
        } else {
            userLogger.info("【用户数据请求】通过用户id = "+ userId +" 请求失败");
            response.getWriter().write(mapper.writeValueAsString(new User()));
        }
    }
}
